from flask import Blueprint, request, jsonify
from app.schemas.user import UserLogin
from app.crud.crud_user import authenticate_user
from app.db.session import get_db

auth = Blueprint('auth', __name__)

@auth.route('/login', methods=['POST'])
def login():
    db = next(get_db())  # 拿一个数据库会话

    data = request.get_json()
    if not data:
        return jsonify({"message": "请求数据为空"}), 400

    user_login = UserLogin(**data)

    token_data = authenticate_user(
        db, email=user_login.email, password=user_login.password, remember=user_login.remember
    )
    if not token_data:
        return jsonify({"message": "邮箱或密码错误"}), 401

    return jsonify(token_data), 200
